<?php

namespace addons\shopro\controller\order;

use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\goods\UserGoodsTransfer;
use DateTime;
use think\Db;
use addons\shopro\controller\Common;
use addons\shopro\service\order\OrderCreate;
use addons\shopro\service\order\OrderOper;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\Pay as PayModel;
use addons\shopro\library\express\Express as ExpressLib;
use think\Request;

class Order extends Common
{

    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

 
    
    public function index()
    {
        $user = auth_user();
        $params = $this->request->param();
        $type = $params['type'] ?? 'all';

        $orders = OrderModel::where('user_id', $user->id)->with(['items', 'invoice']);

        switch ($type) {
            case 'unpaid':
                $orders = $orders->unpaid();
                break;
            case 'nosend':
                $orders = $orders->pretendPaid()->nosend();
                break;
            case 'noget':
                $orders = $orders->pretendPaid()->noget();
                break;
            case 'nocomment':
                $orders = $orders->paid()->nocomment();
                break;
        }

        $orders = $orders->order('id', 'desc')->paginate(request()->param('list_rows', 10))->toArray();

        $orderModel = new OrderModel();
        foreach ($orders['data'] as &$order) {
            $order = $orderModel->setOrderItemStatusByOrder($order);
            $good = Db::name('shopro_goods')->where('id','=',$order['goods_id'])->find();

     
           if($good){
                $order['is_transfer'] = $good['is_transfer'];
           }
           if($order['is_hotels'] == 1){
            if($order['status'] == 'cancel'){
                $order['status_text']="预约失败";
            }else if($order['status'] == 'closed'){
                    $order['status_text']="用户确认中";
            }else if($order['status'] == 'unpaid'){
                    $order['status_text']="预约确定中";
            }else if($order['status'] == 'completed'){
                    $order['status_text']="预约成功";
            }else if($order['status'] == 'paid'){
                    $order['status_text']="预约中";
            }
           }
           $ordertransference = Db::name('user_goods_transference')->Where(['order_sn'=>$order['order_sn']])->find();
           if($ordertransference && $ordertransference ['received_user_id'] >0)
           {
               $order['hidden']=1;
               $order['status_text']='已转让';
           }else
           {
               $order['hidden']=0;
           }
           $starttimetemp =strtotime($order['start_date']);
           $starttime =strtotime('+1 day',$starttimetemp);
           $currentTime = date('Y-m-d H:i:s');
        if($currentTime >= $order['start_date']){
            $order['queren'] = 1;

        }else{
            $order['queren'] = 0;
        }
           $curtime = strtotime("first day of last month");
            if($starttime >=$curtime)
            {
                $order['btns']= 'apply_refund';
                $order['hotelBtn']=1;
            }
            else{
                
               $order['hotelBtn']=0;
            }   
        }

        $this->success('获取成功', $orders);
    }


    public function detail()
    {
        $user = auth_user();
        $id = $this->request->param('id');
        $merchant_trade_no = $this->request->param('merchant_trade_no');
        $transaction_id = $this->request->param('transaction_id');

        $order = OrderModel::where('user_id', $user->id)->with(['items', 'address', 'invoice']);

        if ($id) {
            $order = $order->where(function ($query) use ($id) {
                return $query->where('id', $id)->whereOr('order_sn', $id);
            });
        } else if ($merchant_trade_no) {
            $pay = PayModel::where('pay_sn', $merchant_trade_no)->findOrFail();
            $order = $order->where('id', $pay->order_id);
        } else {
            $this->error('参数错误');
        }

        $order = $order->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order->pay_types_text = $order->pay_types_text;
        // 处理未支付订单 item status_code
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了

        // 更新包裹信息（5分钟缓存）
        (new ExpressLib)->updateOrderExpress($order['id']);
        
        $this->success('获取成功', $order);
    }


    public function itemDetail()
    {
        $user = auth_user();

        $id = $this->request->param('id');
        $item_id = $this->request->param('item_id');

        if (!$id || !$item_id) {
            $this->error('参数错误');
        }

        $order = OrderModel::with(['items' => function ($query) use ($item_id) {
            $query->where('id', $item_id);
        }])->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order || !$order->items) {
            $this->error(__('No Results were found'));
        }

        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        $item = $order['items'][0];

        $this->success('获取成功', $item);
    }


    public function calc()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".calc");

        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->calc();

        if (isset($result['msg']) && $result['msg']) {
            $this->error($result['msg'], 1, $result);
        } else {
            $this->success('计算成功', $result);
        }
    }


    public function create()
    {
        $params = $this->request->param();
        $this->svalidate($params, ".create");
        $user = auth_user();
        $goodsList = $params['goods_list'] ?? [];
    
        $goodsIds = array_column($goodsList, 'goods_id');
        $goodsInfoList = Goods::where('id', 'in', $goodsIds)->select();
        $transferIds = [];
        foreach ($goodsInfoList as $goodsInfo) {
            if ($goodsInfo->is_transfer == 1) {
                $transferIds[] = $goodsInfo->id;
            }
        }
        if (!empty($transferIds)) {
            $transferGoodsInfoList = UserGoodsTransfer::where('goods_id', 'in', $transferIds)->select();
            foreach ($transferGoodsInfoList as $transfer) {
                if ($user->id == $transfer->user_id) {
                    $this->error('不能购买自己转让的商品');
                }
            }
        }
        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->calc('create');

        if($goodsIds && $goodsIds[0])
        {
            $result['goods_id'] = $goodsIds[0];
            
        }
        if($params['order_type'] == 'score' && $params['is_hotels'] == 1 ){

            $result['is_hotels'] = 1;
            $user_time = $result['goods_list'][0]['current_sku_price']['goods_sku_text'];
            $user_time_list = $user_time['0'].'-'.$user_time['1'].'-'.$user_time['2'];
            $timestamp  = strtotime('-1 month', strtotime($user_time_list));
            $start_date = date('Y-m-01', $timestamp);
            //$result['goods_list'][0]['current_sku_price']['start_date'] = $start_date;
            $result['start_date'] = $start_date;

        }else{
            $result['is_hotels'] = 2;
            $result['start_date'] = date('Y-m-d H:i:s');
        }


        // echo "<pre>";
        // print_r($result['user_coupon_ids']);die;


        $order = $orderCreate->create($result);

        $this->success('订单添加成功', $order);
    }

    /**
     * 申请发货
     * @param Request $request
     * @param int $order_id
     * @return void
     */
    public function applydeliver()
    {
        $user = auth_user();
        $orderId = $this->request->param('order_id');
  
        $order = Db::transaction(function () use ($orderId, $user) {
            $order = OrderModel::where('id', $orderId)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }
            if ($order->user_id != $user->id) {
                $this->error("不能处理他人订单");
            }

            $orderOper = new OrderOper();
            $order = $orderOper->applyDeliver($order);
            return $order;
        });

        $this->success('申请成功', $order);
    }
    public function applydeliverno()
    {
        $user = auth_user();
        $orderId = $this->request->param('order_id');
  
        $order = Db::transaction(function () use ($orderId, $user) {
            $order = OrderModel::where('id', $orderId)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }
            if ($order->user_id != $user->id) {
                $this->error("不能处理他人订单");
            }

            $orderOper = new OrderOper();
            $order = $orderOper->applyDeliverno($order);

            return $order;
        });

        $this->success('申请成功', $order);
    }

    /**
     * 转让订单撤销
     * @param int $order_id
     * @return void
     */
    public function transcancel()
    {
        $user = auth_user();
        $orderId = $this->request->param('order_id');
        $order = Db::transaction(function () use ($orderId, $user) {
            $order = OrderModel::where('id', $orderId)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }
            if ($order->user_id != $user->id) {
                $this->error("不能处理他人订单");
            }
            if ($order->status != 'transference') {
                $this->error("不能撤销非转让订单");
            }

            $ordertransference = Db::name('user_goods_transference')->Where(['order_sn'=>$order['order_sn']])->find();
            if($ordertransference && $ordertransference ['received_user_id'] >0)
            {
                $this->error("订单已转让");
            }


            $orderOper = new OrderOper();
            $order = $orderOper->orderTransCancel($order, $user);

            return $order;
        });

        $this->success('订单已撤销', $order);
    }

    /**
     * 订单转让
     * @param Request $request
     * @param int $order_id 转让订单
     * @param int $price  转让价格
     * @return void
     */
    public function transference()
    {
        $user = auth_user();
        $orderId = $this->request->param('order_id');
        $orderPrice = $this->request->param('price');
        $order = Db::transaction(function () use ($orderId, $orderPrice, $user) {
            $order = OrderModel::where('id', $orderId)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }
            if ($order->user_id != $user->id) {
                $this->error("不能处理他人订单");
            }
            if ($order->status == 'transference') {
                $this->error("订单转让中，请不要重复操作");
            }

            $orderOper = new OrderOper();
            $order = $orderOper->orderTransference($order, $user, $orderPrice);

            return $order;
        });

        $this->success('申请成功', $order);
    }



    /**
     * 获取用户可用和不可用优惠券
     *
     * @param Request $request
     * @return void
     */
    public function coupons() 
    {
        $params = $this->request->param();
        $this->svalidate($params, ".create");

        $orderCreate = new OrderCreate($params);
        $result = $orderCreate->getCoupons();

        $this->success('获取成功', $result);
    }



    // 取消订单
    public function cancel()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = Db::transaction(function () use ($id, $user) {
            $order = OrderModel::canCancel()->where('user_id', $user->id)->with(['items', 'invoice'])->lock(true)->where('id', $id)->find();
            if (!$order) {
                $this->error(__('No Results were found'));
            }

            $orderOper = new OrderOper();
            $order = $orderOper->cancel($order, $user, 'user');

            return $order;
        });
        // 订单未支付，处理 item 状态
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了

        $this->success('取消成功', $order);
    }


    // 订单申请全额退款
    public function applyRefund() 
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->applyRefund($order, $user, 'user');

            return $order;
        });

        $order = OrderModel::with(['items', 'invoice'])->find($id);
        $order = $order->setOrderItemStatusByOrder($order);     // 这里订单转 数组了
        $this->success('申请成功', $order);
    }

    // 确认收货(货到付款的确认收货在后台)
    public function confirm()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->confirm($order, [], $user, 'user');

            return $order;
        });

        $order = OrderModel::with(['items', 'invoice'])->find($id);
        $this->success('收货成功', $order);
    }


    // 评价
    public function comment()
    {
        $user = auth_user();
        $params = $this->request->param();
        $id = $params['id'] ?? 0;
        $this->svalidate($params, ".comment");

        $comments = $params['comments'] ?? [];
        foreach ($comments as $comment) {
            $this->svalidate($comment, ".comment_item");
        }

        $order = OrderModel::paid()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error(__('No Results were found'));
        }

        $order = Db::transaction(function () use ($order, $params, $user) {
            $orderOper = new OrderOper();
            $order = $orderOper->comment($order, $params['comments'], $user, 'user');

            return $order;
        });

        $this->success('评价成功', $order);
    }



    /**
     * 用户是否存在未支付的，当前团的订单
     *
     * @param Request $request
     * @return void
     */
    public function unpaidGrouponOrder()
    {
        $user = auth_user();

        $params = $this->request->param();
        $activity_id = $params['activity_id'] ?? 0;

        if ($user && $activity_id) {
            $order = OrderModel::unpaid()->where('user_id', $user->id)
                ->where('activity_id', $activity_id)
                ->whereIn('activity_type', ['groupon', 'groupon_ladder'])->find();
        }

        $this->success('获取成功', $order ?? null);
    }


    // 删除订单
    public function delete()
    {
        $user = auth_user();
        $id = $this->request->param('id');

        $order = OrderModel::canDelete()->where('user_id', $user->id)->where('id', $id)->find();
        if (!$order) {
            $this->error('订单不存在或不可删除');
        }

        Db::transaction(function () use ($order, $user) {
            $orderOper = new OrderOper();
            $orderOper->delete($order, $user, 'user');
        });

        $this->success('删除成功');
    }

    public function updatestatus(){
        $orderid  = input('param.orderid'); 
        $res['status'] = 'unpaid';
        $res['is_queren'] = 1;
        $row = Db::name('shopro_order')->where('id',$orderid)->update($res);
        if($row){
            $this->success('请求成功',$row);    
        }
    }

  
}
